<template>
	<div class="add-change-category">
		<div class="goods-list">
			<div v-for="(item, index) in goodsList" :key="index" class="goods-item">
				<div class="item-header">
					<span class="item-title">商品 {{ index + 1 }}</span>
					<el-button
						v-if="goodsList.length > 1"
						size="small"
						type="danger"
						@click="removeCategory(index)"
					>
						删除
					</el-button>
				</div>
				<el-form :model="item" label-width="120px">
					<el-row :gutter="20">
						<el-col :span="12">
							<el-form-item
								label="商品名称"
								prop="goodsName"
								:rules="[
									{ required: true, message: '请输入商品名称', trigger: 'blur' }
								]"
							>
								<el-input
									v-model="item.goodsName"
									placeholder="请输入商品名称"
									clearable
								/>
							</el-form-item>
						</el-col>

						<el-col :span="12">
							<el-form-item
								label="商品单价"
								prop="goodsPrice"
								:rules="[
									{ required: true, message: '请输入商品单价', trigger: 'blur' }
								]"
							>
								<el-input
									v-model="item.goodsPrice"
									placeholder="请输入商品单价"
									@input="handlePriceInput(index)"
									clearable
								/>
							</el-form-item>
						</el-col>

						<el-col :span="24">
							<el-form-item
								label="商品图片"
								prop="goodsPic"
								:rules="[
									{ required: true, message: '请上传商品图片', trigger: 'blur' }
								]"
							>
								<cl-upload
									v-model="item.goodsPic"
									:limit="1"
									:props="{ action: '/api/file/upload' }"
								/>
							</el-form-item>
						</el-col>
					</el-row>
				</el-form>
			</div>
		</div>
		<el-button type="primary" @click="addGoods">添加商品</el-button>
	</div>
</template>

<script lang="ts" setup>
import { ref, reactive, watch, defineEmits, defineProps } from 'vue';
import { ElMessage, ElMessageBox } from 'element-plus';
import { service } from '/@/cool';

defineOptions({
	name: 'add-goods-item'
});

// Props
const props = defineProps({
	modelValue: {
		type: [Object, Array],
		default: () => []
	},
	clearable: {
		type: Boolean,
		default: false
	}
});

// Emits
const emit = defineEmits(['update:modelValue', 'change']);

// 创建单个商品对象的函数 - 统一使用API返回的字段名
const createGoodsItem = () => ({
	id: null, // 添加id字段，默认为null
	goodsName: '', // 改为goodsName，与API返回一致
	goodsPrice: '',
	goodsPic: '' // 改为goodsPic，与API返回一致
});

// 商品列表
const goodsList = reactive([createGoodsItem()]);

// 处理价格输入的优化方法
const handlePriceInput = (index: number) => {
	try {
		// 直接从goodsList获取当前值
		let value = goodsList[index].goodsPrice || '';

		// 确保值为字符串
		value = String(value);

		// 过滤非数字和小数点
		const filteredValue = value.replace(/[^0-9.]/g, '');

		// 确保只有一个小数点
		const parts = filteredValue.split('.');
		let formattedValue = parts[0];
		if (parts.length > 1) {
			formattedValue += '.' + parts.slice(1).join('');
		}

		// 使用Vue的响应式更新方式
		goodsList[index].goodsPrice = formattedValue;
	} catch (error) {
		console.error('处理价格输入时出错:', error);
	}
};

// 添加商品
const addGoods = () => {
	// 创建新商品时临时禁用 watch 更新
	const newItem = createGoodsItem();
	goodsList.push(newItem);
};

// 删除商品
const removeCategory = (index: number) => {
	const id = goodsList[index].id;
	if (id) {
		// 弹出确认对话框
		ElMessageBox.confirm('点击确定后将立即删除该商品，是否继续？', '删除确认', {
			confirmButtonText: '确定',
			cancelButtonText: '取消',

			type: 'warning'
		})
			.then(() => {
				// 确认删除后发送请求
				service.order.goods
					.delete({ ids: Number(id) })
					.then(res => {
						ElMessage.success('删除成功');
						goodsList.splice(index, 1);
					})
					.catch(() => {
						ElMessage.error('删除失败');
					});
			})
			.catch(() => {
				// 取消删除
				ElMessage.info('已取消删除');
			});
	} else {
		goodsList.splice(index, 1);
	}
};

// 监听外部值变化 - 支持字段名转换
watch(
	() => props.modelValue,
	newVal => {
		// 确保newVal是有效数据
		if (newVal) {
			// 清空当前列表
			goodsList.splice(0);

			if (Array.isArray(newVal)) {
				if (newVal.length > 0) {
					newVal.forEach(item => {
						// 转换字段名，确保数据格式一致
						const convertedItem = {
							id: item.id || null, // 添加id字段处理
							goodsName: item.goodsName || item.categoryName || '',
							goodsPrice: item.goodsPrice || '',
							goodsPic: item.goodsPic || item.categoryPic || ''
						};
						goodsList.push(convertedItem);
					});
				} else {
					// 确保至少有一个商品项
					goodsList.push(createGoodsItem());
				}
			} else if (typeof newVal === 'object') {
				// 兼容单个商品对象的情况，转换字段名
				const convertedItem = {
					id: newVal.id || null, // 添加id字段处理
					goodsName: newVal.goodsName || newVal.categoryName || '',
					goodsPrice: newVal.goodsPrice || '',
					goodsPic: newVal.goodsPic || newVal.categoryPic || ''
				};
				goodsList.push(convertedItem);
			}
		}
	},
	{ deep: true, immediate: true } // 启用深度监听和立即执行，确保能正确初始化数据
);

// 使用防抖函数来减少更新频率，确保返回正确的数组格式
let updateTimer: number | null = null;
const debouncedUpdate = (newVal: any) => {
	if (updateTimer) {
		clearTimeout(updateTimer);
	}
	updateTimer = setTimeout(() => {
		// 确保数据始终为数组格式 [{},{}...]
		const arrayData = Array.isArray(newVal) ? newVal : [newVal];
		// 过滤掉空对象或无效数据
		const validData = arrayData.filter(item => item && typeof item === 'object');
		// 深拷贝数据，避免引用问题
		const clonedData = JSON.parse(JSON.stringify(validData.length > 0 ? validData : []));
		// 始终返回数组格式给父组件的goodsCategory属性
		emit('update:modelValue', clonedData);
		emit('change', clonedData);
	}, 100); // 调整延迟以提高响应速度
};

// 监听内部值变化，同步到外部 - 恢复 deep 监听以确保所有字段变更都能被捕获
watch(goodsList, debouncedUpdate, { deep: true });

// 暴露方法给父组件
defineExpose({
	// 暴露goodsList，便于父组件访问和验证
	goodsList,

	// 获取表单数据 - 确保返回正确的数组格式 [{},{}...]
	getValue() {
		// 确保返回数组格式，过滤空值
		const validData = goodsList.filter(
			item => item && (item.goodsName || item.goodsPrice || item.goodsPic)
		);
		return validData.length > 0 ? validData : [];
	},

	// 设置表单数据
	setValue(value: any) {
		// 临时禁用 watch 更新，避免循环触发
		const tempGoodsList = [...goodsList]; // 保存当前状态

		if (Array.isArray(value)) {
			goodsList.splice(0);
			if (value.length > 0) {
				value.forEach(item => {
					goodsList.push({ ...item });
				});
			} else {
				goodsList.push(createGoodsItem());
			}
		} else if (value && typeof value === 'object') {
			goodsList.splice(0);
			goodsList.push({ ...value });
		}
	},

	// 清空表单
	clear() {
		goodsList.splice(0);
		goodsList.push(createGoodsItem()); // 修复函数名错误
	}
});
</script>

<style scoped>
.add-change-category {
	padding: 10px;
	background-color: #f5f7fa;
	border-radius: 4px;
}

.goods-list {
	margin-bottom: 20px;
}

.goods-item {
	padding: 15px;
	background-color: #fff;
	border-radius: 4px;
	margin-bottom: 20px;
	border: 1px solid #ebeef5;
}

.item-header {
	display: flex;
	justify-content: space-between;
	align-items: center;
	margin-bottom: 15px;
	padding-bottom: 10px;
	border-bottom: 1px solid #ebeef5;
}

.item-title {
	font-weight: 600;
	color: #303133;
}

.el-form-item {
	margin-bottom: 20px;
}
</style>
